﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace NASM_Develop_IDE
{
    class ErrorLineNumbersExtracter
    {
        private string output;
        public ErrorLineNumbersExtracter(string output)
        {
            this.output = output;
        }
        public Dictionary<int, string> GetLineNumbers()
        {
            Dictionary<int, string> lineNumbers = new Dictionary<int, string>();
            Regex pathRegex = new Regex(@"(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.]+)\\(?:[\w]+\\)*\w([\w.])+$");
            Regex numberRegex = new Regex(@"^\d+$");
            List<string> errorLines = output.Replace("\r", "").Split('\n').ToList();
            errorLines.ForEach(delegate(string errorLine)
            {
                if (errorLine != "")
                {
                    List<string> paths = pathRegex.Split(errorLine.Substring(0, errorLine.LastIndexOf(".asm") + 4)).ToList();
                    if (paths.Count > 0)
                    {
                          string path = paths[0];
                          string lineNumberStr = getLineNumberString(errorLine);
                          lineNumbers.Add(int.Parse(lineNumberStr), Path.GetFileName(path));
                    }
                }
            });

            return lineNumbers;
        }
        private string getLineNumberString(string line)
        {
            StringBuilder lineNumberString = new StringBuilder();
            List<char> characters =  line.ToList();
            int index = characters.FindIndex((char c) => (char.IsDigit(c)));
            lineNumberString.Append(characters[index]);
            int endIndex = characters.FindLastIndex((char c) => (char.IsDigit(c)));
            for (index += 1;  index <= endIndex; index++)
            {
                if (!char.IsDigit(characters[index]))
                {
                    return null;
                }
                else
                {
                    lineNumberString.Append(characters[index]);
                }
            }
            return lineNumberString.ToString();
        }
    }
}
